<template>
    <div class="main-container">
        <!-- 查询条件 -->
        <div class="query-container">
            <div class="query-title">查询条件</div>
            <div class="query-condition">
                <el-form ref="queryParams" :model="queryParams" label-width="80px" size="mini" inline>
                    <el-row>
                        <el-form-item label="角色名称">
                            <el-input v-model="queryParams.roleName" placeholder="请输入角色名称"></el-input>
                        </el-form-item>
                        <el-form-item label="角色标识">
                            <el-input v-model="queryParams.roleKey" placeholder="请输入角色标识"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="queryTableList" type="primary">查询</el-button>
                            <el-button @click="resetQueryForm">重置</el-button>
                        </el-form-item>
                    </el-row>
                </el-form>
            </div>
        </div>
        <!-- 按钮工具栏 -->
        <div class="query-button-toolbar">
            <el-button @click="openAddOrEditDialog('')" type="primary" size="mini">新 增</el-button>
        </div>
        <!-- 查询结果 -->
        <div class="query-container">
            <div class="query-title">查询结果</div>
            <div class="query-table">
                <el-table :data="tableData" v-loading="loading" style="width: 100%" size="small" empty-text="空空如也"
                          stripe border>
                    <el-table-column type="index" label="序号" width="50"></el-table-column>
                    <el-table-column prop="roleName" label="角色名称" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="roleKey" label="角色标识" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="createTime" label="创建日期" show-overflow-tooltip></el-table-column>
                    <el-table-column fixed="right" label="操作" width="180">
                        <template slot-scope="scope">
                            <el-button @click="openDetailDialog(scope.row)" type="text" size="small">查看</el-button>
                            <el-button @click="openAddOrEditDialog(scope.row)" type="text" size="small">编辑</el-button>
                            <el-button @click="deleteAction(scope.row.rid)" type="text" size="small">删除</el-button>
                            <el-button @click="openPermsDialog(scope.row.rid)" type="text" size="small">分配权限</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页条件 -->
                <pagination small
                            v-show="pageParams.pageCount > 0"
                            :total="pageParams.pageCount"
                            :page.sync="pageParams.pageNum"
                            :limit.sync="pageParams.pageSize"
                            @pagination="queryTableList"/>
            </div>
        </div>

        <!-- 新增修改弹出框 -->
        <el-dialog :title="dialog.title" :visible.sync="dialog.visible"
                   :close-on-click-modal="dialog.closeOnClickModal">
            <el-form :model="createForm" :rules="createFormRules" ref="createForm" size="mini">
                <el-input v-model="createForm.rid" v-show="false"></el-input>
                <el-form-item label="角色标识" label-width="120px" prop="roleKey">
                    <el-input v-model="createForm.roleKey" placeholder="请输入角色标识"></el-input>
                </el-form-item>
                <el-form-item label="角色名称" label-width="120px" prop="roleName">
                    <el-input v-model="createForm.roleName" placeholder="请输入角色名称"></el-input>
                </el-form-item>
                <el-form-item label="备注" label-width="120px">
                    <el-input type="textarea" v-model="createForm.remark" placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button
                    type="primary"
                    size="mini"
                    v-if="dialog.btnType"
                    @click="addRole"
                >新 增
                </el-button>
                <el-button type="primary" size="mini" v-else @click="editRole"
                >编 辑
                </el-button>
                <el-button size="mini" @click="closeAddAndEditDialog">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 查看角色详情 -->
        <el-dialog
            title="查看详情"
            :visible.sync="detailDialog.visible"
            :close-on-click-modal="closeOnClickModal"
        >
            <el-descriptions class="margin-top" :column="2" border>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-user"></i>
                        角色ID
                    </template>
                    {{ detailRoleInfo.rid }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-user"></i>
                        角色名称
                    </template>
                    {{ detailRoleInfo.roleName }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-user"></i>
                        角色标识
                    </template>
                    {{ detailRoleInfo.roleKey }}
                </el-descriptions-item>
                <el-descriptions-item :span="2">
                    <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        备注
                    </template>
                    {{ detailRoleInfo.remark }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        创建日期
                    </template>
                    {{ detailRoleInfo.createTime }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template slot="label">
                        <i class="el-icon-mobile-phone"></i>
                        角色状态
                    </template>
                    <el-tag type="success" v-if="detailRoleInfo.enabled === '01'"
                    >启用
                    </el-tag
                    >
                    <el-tag type="danger" v-if="detailRoleInfo.enabled === '02'"
                    >禁用
                    </el-tag
                    >
                </el-descriptions-item>
            </el-descriptions>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" @click="closeDetailDialog"
                >关 闭
                </el-button
                >
            </div>
        </el-dialog>

        <!-- 分配权限 -->
        <el-dialog
            title="分配权限"
            :visible.sync="permsDialog.visible"
            :close-on-click-modal="closeOnClickModal"
        >
            <el-scrollbar style="height: 380px;" wrap-class="scrollbar-wrapper">
                <el-tree
                    :data="menuTreeData"
                    ref="menuTree"
                    show-checkbox
                    node-key="mid"
                    empty-text="空空如也"
                    default-expand-all
                    :expand-on-click-node="false"
                    :check-on-click-node="true"
                    check-strictly
                    :props="{ children: 'children', label: 'menuName' }">
                </el-tree>
            </el-scrollbar>
            <div slot="footer" class="dialog-footer">
                <el-button @click="assignMenu" type="primary" size="mini">分 配</el-button>
                <el-button @click="closePermsDialog" size="mini">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    createRole,
    removeRole,
    updateRole,
    assignMenuToRole,
    queryPage,
} from "@/api/sys/role";
import {
    queryTreeMenu, getRoleMenu
} from "@/api/sys/menu";
import Pagination from "@/components/Pagination";

export default {
    name: "RoleIndex",
    components: {Pagination},
    data() {
        return {
            pageParams: {
                pageCount: 0,
                pageNum: 1,
                pageSize: 10,
            },
            queryParams: {},
            tableData: [],
            menuTreeData: [],
            loading: false,
            queryLoading: false,
            closeOnClickModal: false,
            dialog: {
                title: "新增角色",
                visible: false,
                btnType: true,
            },
            detailDialog: {
                visible: false,
                closeOnClickModal: false,
            },
            permsDialog: {
                visible: false
            },
            createForm: {
                rid: "",
                roleName: "",
                roleKey: "",
                remark: ""
            },
            createFormRules: {
                roleName: [
                    {required: true, message: "请输入角色名称", trigger: "blur"},
                    {min: 6, max: 30, message: "长度在 6 到 30 个字符", trigger: "blur"},
                ],
                roleKey: [
                    {required: true, message: "请输入角色标识", trigger: "blur"},
                    {min: 6, max: 30, message: "长度在 6 到 30 个字符", trigger: "blur"},
                ],
            },
            detailRoleInfo: {
                rid: "",
                roleName: "",
                roleKey: "",
                createTime: "",
            },
            currentRoleId: ''
        };
    },
    created() {
        this.queryTableList();
    },
    methods: {
        /** 查询表格数据 */
        queryTableList() {
            const _this = this;
            _this.queryParams.pageNum = _this.pageParams.pageNum;
            _this.queryParams.pageSize = _this.pageParams.pageSize;
            _this.loading = true;
            queryPage(_this.queryParams).then((resp) => {
                if (resp.code === 20000) {
                    _this.tableData = resp.data.record;
                    _this.pageParams.pageNum = resp.data.pageNum;
                    _this.pageParams.pageSize = resp.data.pageSize;
                    _this.pageParams.pageCount = resp.data.pageCount;
                } else {
                    _this.$message.warning(resp.message);
                }
                _this.loading = false;
            }).catch((error) => {
                _this.$message.warning(error.message);
                _this.loading = false;
            });
        },
        /** 重置查询条件 */
        resetQueryForm() {
            console.log("reset form");
            this.queryParams = {};
        },
        /** 删除操作 */
        deleteAction(id) {
            const _this = this;
            _this.$confirm("是否删除当前行数据?", "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnClickModal: false,
                type: "warning",
            }).then(() => {
                removeRole(id).then((resp) => {
                    if (resp.code === 20000) {
                        _this.$message.success(resp.message);
                        _this.queryTableList();
                    } else {
                        _this.$message.warning(resp.message);
                    }
                }).catch((error) => {
                    _this.$message.warning(error.message);
                });
            });
        },
        /** 打开编辑弹出框 */
        openAddOrEditDialog(row) {
            const _this = this;
            _this.$nextTick(function () {
                console.log("row-->:", row);
                if (row) {
                    // 编辑
                    _this.createForm.rid = row.rid;
                    _this.createForm.roleName = row.roleName;
                    _this.createForm.roleKey = row.roleKey;
                    _this.createForm.remark = row.remark;
                    _this.dialog.title = "编辑角色";
                    _this.dialog.btnType = false;
                } else {
                    // 新增
                    _this.dialog.title = "新增角色";
                    _this.dialog.btnType = true;
                }
                console.log("open dialog");
                _this.dialog.visible = true;
            });
        },
        /** 新增角色 */
        addRole() {
            const _this = this;
            _this.$refs.createForm.validate((valid) => {
                if (valid) {
                    createRole(_this.createForm).then((resp) => {
                        if (resp.code === 20000) {
                            _this.$message.success(resp.message);
                            _this.closeAddAndEditDialog();
                            _this.queryTableList();
                        } else {
                            _this.$message.warning(resp.message);
                        }
                    }).catch((error) => {
                        _this.$message.warning(error.message);
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        /** 编辑角色 */
        editRole() {
            const _this = this;
            _this.$refs.createForm.validate((valid) => {
                if (valid) {
                    updateRole(_this.createForm).then((resp) => {
                        if (resp.code === 20000) {
                            _this.$message.success(resp.message);
                            _this.closeAddAndEditDialog();
                            _this.queryTableList();
                        } else {
                            _this.$message.warning(resp.message);
                        }
                    }).catch((error) => {
                        _this.$message.warning(error.message);
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        /** 关闭弹出框 */
        closeAddAndEditDialog() {
            this.resetCreateForm();
            this.dialog.visible = false;
            console.log("close dialog");
        },
        /** 打开查看详情弹出框 */
        openDetailDialog(row) {
            console.log("open dialog");
            const _this = this;
            _this.$nextTick(function () {
                _this.detailRoleInfo.rid = row.rid;
                _this.detailRoleInfo.roleName = row.roleName;
                _this.detailRoleInfo.roleKey = row.roleKey;
                _this.detailRoleInfo.remark = row.remark;
                _this.detailRoleInfo.createTime = row.createTime;
                _this.detailDialog.visible = true;
            });
        },
        /** 关闭查看详情弹出框 */
        closeDetailDialog() {
            this.detailDialog.visible = false;
            console.log("close dialog");
        },
        /** 重置表单 */
        resetCreateForm() {
            this.createForm.rid = "";
            this.createForm.roleKey = "";
            this.createForm.roleName = "";
            this.createForm.remark = "";
            this.$refs.createForm.clearValidate();
        },
        /** 查询权限书 */
        getTreeMenuList() {
            queryTreeMenu().then(resp => {
                if (resp.code === 20000) {
                    this.menuTreeData = resp.data;
                } else {
                    this.$message.warning(resp.message);
                }
            }).catch(error => {
                this.$message.warning(error.message);
            });
        },
        /** 打开分配权限弹出框 */
        async openPermsDialog(rid) {
            await this.getTreeMenuList();
            this.permsDialog.visible = true;
            this.currentRoleId = rid;
            this.$nextTick(function () {
                this.$refs.menuTree.setCheckedKeys([]);
                getRoleMenu(rid).then(response => {
                    if (response.code === 20000) {
                        const item = response.data;
                        const checkedKeys = this.getSelectedTreeNode(this.menuTreeData, item);
                        this.$refs.menuTree.setCheckedKeys(checkedKeys);
                    } else {
                        this.$message.warning(response.message);
                    }
                }).catch(err => {
                    this.$message.warning(err.message);
                });
            });
        },
        /** 获取选中的Node结点 */
        getSelectedTreeNode(menuTreeList, selectedTreeList) {
            const checkedKeys = [];
            return this.mapCheckedKeys(menuTreeList, selectedTreeList, checkedKeys);
        },
        mapCheckedKeys(menuTreeList, selectedTreeList, checkedKeys) {
            menuTreeList.forEach(item => {
                if (item.children !== null && item.children.length > 0) {
                    this.mapCheckedKeys(item.children, selectedTreeList, checkedKeys);
                } else {
                    // 判断当前结点是否选中
                    selectedTreeList.forEach(curNode => {
                        if (item.mid === curNode.mid) {
                            checkedKeys.push(item.mid);
                        }
                    });
                }
            });
            return checkedKeys;
        },
        /** 关闭分配权限弹出框 */
        closePermsDialog() {
            this.permsDialog.visible = false;
            this.currentRoleId = '';
            this.$refs.menuTree.setCheckedKeys([]);
        },
        /** 确认分配权限 */
        assignMenu() {
            // 判断是否选择权限
            const checkedNodes = this.$refs.menuTree.getCheckedNodes();
            console.log('---->:', checkedNodes)
            // 准备请求参数
            let params = [];
            for (let i = 0; i < checkedNodes.length; i++) {
                let relaObj = {
                    rid: this.currentRoleId,
                    mid: checkedNodes[i].mid
                };
                params.push(relaObj);
            }
            assignMenuToRole(params).then(resp => {
                if (resp.code === 20000) {
                    this.$message.success(resp.message);
                    this.closePermsDialog();
                } else {
                    this.$message.warning(resp.message);
                }
            }).catch(error => {
                this.$message.warning(error.message);
            });
        }
        /** methods end */
    },
};
</script>

<style lang="scss" scoped>
</style>